<template>
  <div class="container">
    <!-- <el-button type="primary" @click="printHandle">打印</el-button> -->
    <div class="sidebar">
      <el-row>
        <el-col :span="5" :offset="2">
          <el-image
            v-if="this.user.url != undefined"
            :src="this.user.url"
            style="width: 200px; height: 200px"
          >
          </el-image>
        </el-col>
        <el-col :span="8" :offset="7">
          <el-card>
            <!-- 右边区域，从上到下显示 ID、姓名和身份 -->
            <el-form :model="user" label-width="80px">
              <el-form-item label="店员ID">
                <span>{{ user.id }}</span>
              </el-form-item>
              <el-form-item label="姓名">
                <span>{{ user.name }}</span>
              </el-form-item>
              <el-form-item label="身份">
                <span>
                  {{
                    user.level === 1 ? "管理员" : user.level === 0 ? "店员" : ""
                  }}</span
                >
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
      <el-divider />
      <el-row>
        <el-col :span="12" :offset="5">
          <span style="display: block; text-align: center">扫描录入</span>
          <el-input
            v-model="barcode"
            maxlength="13"
            clearable
            @keyup.enter.native="getProduct"
            ref="editTask"
          ></el-input>
        </el-col>
        <el-col>
          <el-divider></el-divider>
        </el-col>
        <el-col>
          <el-form>
            <el-row>
              <el-col :span="7">
                <!-- 这里放置物品照片的内容 -->
                <el-card style="width: 250px; height: 250px">
                  <el-image
                    v-if="this.goods.url != ''"
                    :src="this.goods.url"
                    style="width: 200px; height: 200px"
                  >
                  </el-image
                ></el-card>
              </el-col>
              <el-col :span="10" :offset="5">
                <!-- 这里嵌套一个el-row用于名称和单价的上下显示 -->
                <el-card>
                  <el-form-item label="名称">
                    <span class="el-input">{{ this.goods.name }}</span>
                  </el-form-item>
                  <el-form-item label="单价">
                    <span class="el-input">
                      {{ this.goods.price }}
                      <template v-if="this.goods.price"> 元 </template>
                    </span>
                  </el-form-item>
                </el-card>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <div class="content">
      <el-container>
        <el-main>
          <el-card>
            <el-table :data="this.orders.shopCarList" :height="500">
              <el-table-column
                label="商品名"
                prop="productName"
                min-width="10%"
              >
              </el-table-column
              ><el-table-column
                label="单价(元)"
                prop="price"
                :formatter="rounding"
                min-width="10%"
              >
              </el-table-column>
              <el-table-column min-width="5%" label="">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="sup(scope.$index, scope.row)"
                    round
                    >-</el-button
                  >
                </template>
              </el-table-column>
              ><el-table-column
                label="数量"
                prop="num"
                min-width="7%"
                align="center"
              >
                <template slot-scope="scope">
                  <el-input
                    @keyup.enter.native="toNum(scope.row)"
                    v-model="scope.row.num"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column min-width="6%" label="">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="success"
                    @click="add(scope.$index, scope.row)"
                    round
                    >+</el-button
                  >
                </template>
              </el-table-column>

              <el-table-column min-width="5%" label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="del(scope.row)"
                    >删除</el-button
                  ></template
                >
              </el-table-column>
            </el-table>
          </el-card>
        </el-main>
        <el-footer>
          <el-divider />
          <el-card>
            <el-row>
              <el-col :span="12">
                <span>
                  总价{{ this.orders.totalPrice
                  }}<template v-if="this.orders.totalPrice"> 元 </template>
                </span>
              </el-col>
              <el-col :span="12">
                <el-button @click="submit">提交订单</el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-footer>
      </el-container>
    </div>
    <el-dialog title="收款码" :visible.sync="dialogVisible" width="50%">
      <div>
        <span>
          <el-row align="center">
            <el-col :span="12" align="center">
              <el-card
                ><img
                  src="../assets/images/1697606697185.jpg"
                  alt=""
                  style="width: 300px"
                  align="center"
                />
              </el-card>
            </el-col>
            <el-col :span="12" align="center">
              <el-card>
                <img
                  src="../assets/images/mm_facetoface_collect_qrcode_1697606247229.png"
                  alt=""
                  style="width: 300px"
                  align="center"
              /></el-card>
            </el-col>
          </el-row>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="printOn">确 定</el-button>
        </span>
      </div>
    </el-dialog>
    <el-dialog
      title=""
      :visible.sync="printThis"
      width="20%"
      :before-close="handleClose"
      ><div id="printMe">
        <el-container>
          <div class="container2">
            <el-head>
              <span style="font-size: 30px">开 心 每 一 天</span>
            </el-head>
          </div>
          <el-divider />
          <div style="display: flex; flex-direction: column">
            <span>订单号: {{ this.orders.ordersId }}</span>
            <span>柜员号: {{ this.orders.userId }}</span>
          </div>
          <el-main>
            <el-table
              :data="this.orders.shopCarList"
              style="width: 100%"
              :show-header="true"
              height="450"
            >
              <el-table-column prop="productName" label="商品" min-width="10%">
              </el-table-column>
              <el-table-column prop="num" label="数量" min-width="10%">
              </el-table-column>
              <el-table-column
                prop="price"
                label="单价(元)"
                min-width="10%"
                :formatter="rounding"
              ></el-table-column>
              <el-table-column
                min-width="10%"
                label="小结(元)"
                :formatter="rounding"
              >
                <template slot-scope="{ row }"
                  ><span>
                    {{ (row.num * row.price).toFixed(2) }}
                  </span></template
                >
              </el-table-column>
            </el-table></el-main
          >
          <el-footer>
            <div style="display: flex; flex-direction: column">
              <span :formatter="rounding"
                >总价: {{ this.orders.totalPrice }}</span
              >
              <span>时间: {{ this.orders.createTime }}</span>
            </div></el-footer
          >
        </el-container>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="printThis = false">关闭</el-button>
        <el-button type="primary" v-print="'#printMe'" @click="orderFine"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json
import http from "../utils/request";
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      printThis: false,
      dialogVisible: false,
      barcode: "",
      user: {
        name: "",
        permissionLevel: "",
        url: "",
        id: 1,
      },
      goods: {
        name: "",
        price: "",
        url: "",
        productId: "",
      },
      orders: {
        ordersId: "",
        totalPrice: "",
        shopCarList: [],
        userId: "",
        userName: "",
        createTime: "",
      },
      shopCar: [],
      ordersId: 0,
      productId: 0,
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    printOn() {
      this.printThis = true;
    },
    toNum(row) {
      console.log("row", row);
      this.dataSwitch(row.num, row.shopCarId);
    },
    dataSwitch(num, id) {
      http.put(`/car/num?num=${num}&id=${id}`).then(({ data }) => {
        console.log("响应", data);

        this.getOrders();
      });
    },
    add(index, data) {
      console.log("加", data);
      console.log("加", index);
      data.num++;
      this.dataSwitch(data.num, data.shopCarId);
    },
    sup(index, data) {
      if (data.num == 1) {
        this.del(data);
        return;
      }
      console.log("减", data);
      console.log("减", index);
      data.num--;
      this.dataSwitch(data.num, data.shopCarId);
    },
    del(car) {
      console.log("删除这个货品", car);
      http.delete(`/car/delete/${car.shopCarId}`).then(({ data }) => {
        if (data.code == 1) {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.getOrders();
        }
      });
    },
    rounding(row, column) {
      return parseFloat(row[column.property]).toFixed(2);
    },
    orderFine() {
      this.printThis = false;
      console.log("结算该订单", this.orders.ordersId);
      http.put(`order/submit/${this.orders.ordersId}`).then(({ data }) => {
        if (data.code == 1) {
          this.dialogVisible = false;
          this.$message({
            type: "success",
            message: "已支付",
          });
          this.printOn();
          this.orders = {
            ordersId: "",
            totalPrice: "",
            shopCarList: [],
            userId: "",
            userName: "",
            createTime: "",
          };
          this.goods = {
            name: "",
            price: "",
            url: "",
            productId: "",
          };
          this.shopCar = [];
        }
      });
    },
    submit() {
      console.log("长度", this.orders.shopCarList.length);
      if (this.orders.ordersId != "" && this.orders.shopCarList.length > 0) {
        this.dialogVisible = true;
      } else {
        this.$message.error("无订单");
      }
    },
    clearOrder() {
      http.get(`/orde/remove/${this.orders.ordersId}`).then(({ data }) => {
        console.log("清理失效的的订单信息", data);
      });
    },
    getProduct() {
      if (this.barcode.length < 13) {
        this.$message.error("条码数据错误");
        return;
      }
      this.goods = {
        name: "",
        price: "",
        url: "",
        productId: "",
      };
      console.log("获取商品信息", this.barcode);
      http.get(`product/getbybarcode/${this.barcode}`).then(({ data }) => {
        if (data.code == 1) {
          console.log("获取到商品信息", data);
          this.productId = data.data.productId;
          console.log("输入商品id", this.productId);
          this.goods.productId = data.data.productId;
          this.goods.name = data.data.name;
          this.goods.price = data.data.price.toFixed(2);
          this.goods.url = data.data.image;
          this.createOrder();
        } else {
          this.$message.error("未能获取商品信息");
        }
        this.barcode = "";
      });
    },
    createOrder() {
      if (this.orders.ordersId == "") {
        http.put(`order/create/${this.user.id}`).then(({ data }) => {
          this.orders.ordersId = data.data;
          console.info("获取到订单号", this.orders.ordersId);
          this.joinCar();
        });
      } else {
        this.joinCar();
      }
    },
    // getCar() {
    //   http.get(`car/list/${this.orders.ordersId}`).then(({ data }) => {
    //     console.info("获取购物车", data.data);
    //     this.shopCar = data.data;
    //   });
    // },
    joinCar() {
      http
        .put(
          `car/add?orderId=${this.orders.ordersId}&productId=${this.goods.productId}`
        )
        .then(({ data }) => {
          if (data.code != 1) {
            this.$message.error("添加商品失败");
          } else {
            this.getOrders();
          }
        });
    },
    getUserId() {
      this.userId = window.localStorage.getItem("userId");
    },
    getOrders() {
      http.get(`order/get/${this.orders.ordersId}`).then(({ data }) => {
        console.info("获取订单总价", data.data);
        this.orders.shopCarList = data.data.shopCarList;
        this.orders.userId = data.data.userId;
        this.orders.totalPrice = data.data.totalPrice.toFixed(2);
        this.orders.createTime = data.data.createTime;
      });
    },
    inputSet() {
      this.$nextTick(() => this.$refs.editTask.focus());
    },

    getUserInfo() {
      if (this.userId == 0) {
        this.$message.error("员工信息错误", this.userId);
        return;
      }
      // ${this.$UserId}
      http.get(`/user/get/${this.userId}`).then(({ data }) => {
        this.user.name = data.data.name;
        this.user.level = data.data.permissionLevel;
        this.user.url = data.data.avatar;
        this.user.id = data.data.id;
        console.log("接收数据", this.user.url);
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getUserId();
    this.getUserInfo();
    this.inputSet();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {
    this.inputSet();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>

//@import url(); 引入公共 css 类
<style lang="less" scoped>
.container {
  display: flex;
  height: 100vh;
}
.sidebar {
  flex: 6;
  background-color: #ffffff;
  padding: 1px;
}

.content {
  flex: 4;
  padding: 1px;
}
.centered-button {
  display: flex;
  justify-content: center;
}
.container2 {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-head {
  margin-bottom: 20px;
}
</style>
